package com.zang.concurrent.cas;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Zhang Qiang
 * @Date 2019/9/21 17:53
 */
public class CASBaseCounter {
    private volatile long count;
    public long value(){
        return count;
    }
    public void increment(){
        long oldValue;
        long newValue;
        do {
            oldValue = count;
            newValue = oldValue + 1;
        } while (!compareAndSwap(oldValue, newValue));
    }

    /**
     * CAS操作 伪代码
     * 举例 检查如果旧值与新值一直说明不成功
     * @param oldValue
     * @param newValue
     * @return
     */
    private boolean compareAndSwap(long oldValue, long newValue){

        AtomicLong atomicLong = new AtomicLong();

        if (oldValue == newValue-1){
            return false;
        }
        return true;
    }


}
